package com.liury.bbs.controller;

import com.github.pagehelper.PageInfo;
import com.liury.bbs.entity.Kind;
import com.liury.bbs.entity.Reply;
import com.liury.bbs.entity.Title;
import com.liury.bbs.entity.User;
import com.liury.bbs.mapper.KindMapper;
import com.liury.bbs.mapper.ReplyMapper;
import com.liury.bbs.mapper.TitleMapper;
import com.liury.bbs.mapper.UserMapper;
import com.liury.bbs.service.AdminService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;
import com.liury.bbs.utils.ExportExcel;
import com.liury.bbs.utils.ExportExcel2;

@Controller
@RequestMapping("admin")
public class Admincontroller {
    @Autowired
    UserMapper userMapper;
    @Autowired
    AdminService adminService;
    @Autowired
    ReplyMapper replyMapper;
    @Autowired
    TitleMapper titleMapper;
    @Autowired
    KindMapper kindMapper;
    @RequestMapping("tologin")
    public String tologin(){
        return "admin/login";
    }

    @RequestMapping("code")
    @ResponseBody
    public void code(HttpServletRequest request, HttpServletResponse response){
        ValidateCode validateCode = new ValidateCode();
        validateCode.getValidate(response,request);
    }

    @RequestMapping("login")
    public String login(String name, String password, Model model,String mycode, HttpSession session){
        //seesion获取正确验证码
        String code=(String) session.getAttribute("code");
        if(code.equals(mycode)){
            if("admin".equals(name)&&"admin".equals(password)){
                session.setAttribute("admin",name);
                return "admin/index";
            }else {
                model.addAttribute("msg","账户名或密码不正确");
                return "admin/login";
            }
        }else {
            model.addAttribute("msg","验证码不正确");
            return "admin/login";
        }
    }
    @RequestMapping("toIndex")
    public String toIndex(){
        return "admin/index";
    }


    @RequestMapping("getUsers")
    public String getUsers(@RequestParam(defaultValue = "1")Integer pageNo,String key,Model model,HttpSession session){
        PageInfo<User> userPageInfo=adminService.findAllUsers(pageNo,5,key);
        model.addAttribute("userPageInfo",userPageInfo);
        session.setAttribute("userPageInfo",userPageInfo);
        model.addAttribute("key",key);
        return "admin/users";
    }

    @RequestMapping("toAdd")
    public String toAdd(){
        return "admin/add";
    }

    @RequestMapping("add")
    public String add(User user){
        System.out.println(user);
        String data= LocalDateTime.now().toString();
        user.setRegedit_time(data);
        userMapper.insert(user);
        return "redirect:getUsers";
    }

    @RequestMapping("delete")
    public String delete(Integer id,Integer pageNo,String key){
        userMapper.delete(id);
        return "redirect:getUsers?pageNo="+pageNo+"&key="+key;
    }

    @RequestMapping("toEdit")
    public String toEdit(Integer id,Integer pageNo,String key,Model model){
        User u=userMapper.getById(id);
        model.addAttribute("u",u);
        model.addAttribute("key",key);
        model.addAttribute("pageNo",pageNo);
        return "admin/edit";
    }

    @RequestMapping("update")
    public String update(User user,Integer pageNo,String key,Model model){
        userMapper.update(user);
        return "redirect:getUsers?pageNo="+pageNo+"&key="+key;
    }
//类别

    @RequestMapping("typies")
    public String typies(Model model){
        List<Kind> kindList=kindMapper.find();
        System.out.println(kindList);
        model.addAttribute("kindList",kindList);
        return "admin/typies";
    }

    @RequestMapping("toAddType")
    public String toInsertType(){
        return "admin/addType";
    }
    @RequestMapping("insertType")
    public String insertType(Kind kind){
        kindMapper.insertType(kind);
        return "redirect:typies";
    }

    @RequestMapping("deleteType")
    public String deleteType(Integer id){
        kindMapper.deleteType(id);
        return "redirect:typies";
    }

    @RequestMapping("toEditType")
    public String toEditType(Integer id,Model model){
        Kind k=kindMapper.get(id);
        model.addAttribute("k",k);
        return "admin/editType";
    }

    @RequestMapping("updateType")
    public String updateType(Kind kind){
        kindMapper.updateType(kind);
        return "redirect:typies";
    }

    @RequestMapping("getTitles")
    public String getTitles(Title t,  @RequestParam(defaultValue = "1")Integer pageNo,Model model,HttpSession session){
        if("null".equals(t.getTitle())) t.setTitle("");
        if("null".equals(t.getContent())) t.setContent("");
        if(t.getKind_id()==null) t.setKind_id(0);
        PageInfo<Title> titlePageInfo=adminService.getALlTitles(t,pageNo,5);
        model.addAttribute("titlePageInfo",titlePageInfo);
        model.addAttribute("title1",t);
        session.setAttribute("titlePageInfo",titlePageInfo);
        session.setAttribute("title1",t);//方便代码提示
        return "admin/titles";
    }

    //下拉菜单查询类别
    @RequestMapping("getKind")
    @ResponseBody
    public List<Kind> getKind(){
        List<Kind> kindList=kindMapper.find();
        return kindList;
    }

    @RequestMapping("deleteTitle")
    public String deleleTitle(Integer id,Integer pageNo,HttpSession session){
        session.getAttribute("title1");
        titleMapper.deleteTitle(id);
//        return "redirect:getTitles?kind_id="+t.getKind_id()+"&content="+t.getContent()+"&title="+t.getTitle()+"&pageNo="+pageNo;
        Title t=(Title) session.getAttribute("title1");
        return "redirect:getTitles?kind_id="+t.getKind_id() +"&content="+t.getContent()+"&title="+t.getTitle()+"&pageNo="+pageNo;


    }

    @RequestMapping("GoToEditTitle")
    public String GoToEditTitle(Integer id,Integer pageNo,Model model){
        Title t=titleMapper.getTitle(id);
        model.addAttribute("t",t);
        model.addAttribute("pageNo",pageNo);
        return "admin/editTitle";
    }

    @RequestMapping("updateTitle")
    public String updateTitle(Title t,Integer pageNo,HttpSession session){
        titleMapper.updateTitle(t);
        Title t1=(Title) session.getAttribute("title1");
        return "redirect:getTitles?kind_id="+t1.getKind_id() +"&content="+t1.getContent()+"&title="+t1.getTitle()+"&pageNo="+pageNo;
    }

    //查看回帖
    @RequestMapping("getReplies")
    public String getReplies(Reply r,
                             @RequestParam(defaultValue = "1")Integer pageNo,
                             Model model, HttpSession session){
        if("null".equals(r.getContent())) r.setContent("");
        if(r.getTitle_id()==null) r.setTitle_id(0);
        PageInfo<Reply> replyPageInfo=adminService.getAllReplies(r,pageNo,5);
        model.addAttribute("replyPageInfo",replyPageInfo);
        model.addAttribute("r",r);
        session.setAttribute("replyPageInfo",replyPageInfo);
        session.setAttribute("r1",r);
        return "admin/replies";
    }
    @RequestMapping("deleteReply")
    public String deleteReply(Integer id,Integer pageNo,HttpSession session) throws UnsupportedEncodingException {
        Reply r=(Reply) session.getAttribute("r1");
        String content=r.getContent();
        Integer title_id=r.getTitle_id();
        if(content==null) content="";
        content= URLEncoder.encode(content,"utf-8");
        replyMapper.deleteReply(id);
        return "redirect:getReplies?pageNo="+pageNo+"&content="+content+"&title_id="+title_id;
    }

    @RequestMapping("goTOReply")
    public String goTOReply(Integer id,Integer pageNo,Model model,HttpSession session){
        Reply r=replyMapper.getReplyById(id);
        model.addAttribute("r",r);
        model.addAttribute("pageNo",pageNo);
        return "admin/editReply";
    }

    @RequestMapping("updateReply")
    public String updateReply(Reply r,HttpSession session,Integer pageNo) throws UnsupportedEncodingException {
        replyMapper.updateReply(r);
        Reply r1=(Reply) session.getAttribute("r1");
        String content=r1.getContent();
        Integer title_id=r1.getTitle_id();
        if(content==null) content="";
        content= URLEncoder.encode(content,"utf-8");
        return "redirect:getReplies?content="+content+"&title_id="+r1.getTitle_id()+"&pageNo="+pageNo;
    }

    //excel user
    @RequestMapping("export")
    public void export(HttpServletResponse response){
        response.setContentType("octets/stream");
        response.addHeader("Content-Disposition", "attachment;filename=test2.xls");
        //测试
        ExportExcel<User> ex = new ExportExcel<User>();
        String[] headers = {"编号","用户名", "密码", "邮箱","性别","注册时间" };

        try {
            List<User> dataset=userMapper.findAll();//查询所有数据进行输出

            OutputStream out = response.getOutputStream();
            ex.exportExcel(headers, dataset, out);
            out.close();
            System.out.println("excel导出成功！");
        }catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
// excel kind
    @RequestMapping("export1")
    public void export1(HttpServletResponse response){
        response.setContentType("octets/stream");
        response.addHeader("Content-Disposition", "attachment;filename=test2.xls");
        //测试
        ExportExcel2<Kind> ex = new ExportExcel2<Kind>();
        String[] headers = {"编号","类名", "描述" };

        try {
            List<Kind> dataset=kindMapper.find();//查询所有数据进行输出
            OutputStream out = response.getOutputStream();
            ex.exportExcel(headers, dataset, out);
            out.close();
            System.out.println("excel导出成功！");
        }catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }




}
